package com.duowei.dw_pos;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.duowei.dw_pos.bean.CXDMXXX;
import com.duowei.dw_pos.bean.FXHYKSZ;
import com.duowei.dw_pos.bean.ImsCardMember;
import com.duowei.dw_pos.bean.JYXMSZ;
import com.duowei.dw_pos.bean.MZSZJBXX;
import com.duowei.dw_pos.bean.Moneys;
import com.duowei.dw_pos.bean.WMLSB;
import com.duowei.dw_pos.bean.WXFWQDZ;
import com.duowei.dw_pos.bean.Wmslbjb_jiezhang;
import com.duowei.dw_pos.event.ImsCardMembers;
import com.duowei.dw_pos.event.UpdateYhPrice;
import com.duowei.dw_pos.httputils.Post6;
import com.duowei.dw_pos.httputils.Post7;
import com.duowei.dw_pos.summiscan.ScanActivity;
import com.duowei.dw_pos.tools.DateTimeUtils;
import com.duowei.dw_pos.tools.DateTimes;
import com.duowei.dw_pos.tools.Net;
import com.duowei.dw_pos.tools.Users;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.joda.time.DateTime;
import org.litepal.crud.DataSupport;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class YunLandActivity extends AppCompatActivity {

    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.btn_cancel)
    Button mBtnCancel;
    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R.id.btn_shama)
    Button mBtnShama;

    private final int REQUESTCODE = 0;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    private String mPhone;
    private String mPassword;
    private int mWeid;
    private Post6 mPost6;
    private String mSip;
    private ArrayList<WMLSB> mListWmlsb;
    private Serializable mWmlsbjb;
    private float mTotalMoney;
    private ImsCardMember[] mImsCardMembers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yun_land);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ButterKnife.bind(this);
        mPost6 = Post6.getInstance();
        mListWmlsb = (ArrayList<WMLSB>) getIntent().getSerializableExtra("listWmlsb");
        mWmlsbjb = getIntent().getSerializableExtra("WMLSBJB");
        getYunData();

        if((this.getApplicationInfo().flags& ApplicationInfo.FLAG_DEBUGGABLE)!=0){
            mEtPhone.setText("15260202690");
            mEtPassword.setText("362442");
        }
    }

    private void getYunData() {
        List<WXFWQDZ> list = DataSupport.select("weid", "SIP").find(WXFWQDZ.class);
        mWeid = list.get(0).getWeid();
        mSip = "android"+list.get(0).getSIP();
        Net.yunUrl = "http://" + mSip + ":2233/serverandroid/ServerSvlt?";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE && data != null) {
            String result = data.getStringExtra("result").trim();
            if (result.length() <= 0 || !result.contains(",")) {
                Toast.makeText(YunLandActivity.this, "扫描失败，请重试", Toast.LENGTH_SHORT).show();
            } else {
                int x = 0;
                for (int i = 0; i <= result.length() - 1; i++) {
                    String getstr = result.substring(i, i + 1);
                    if (getstr.equals(",")) {
                        x++;
                    }
                }
                if (x >= 2) {
                    mPassword = result.substring(result.indexOf(",") + 1, result.lastIndexOf(",")).trim();
                } else {
                    mPassword = result.substring(result.indexOf(",") + 1, result.length()).trim();
                }
                mEtPhone.setText(mPhone = result.substring(0, result.indexOf(",")));
                mEtPassword.setText(mPassword);
                mPost6.post_ims_card_members(mPhone, mPassword, mWeid);//发送post请求云会员登录

                mProgressBar.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    /**
     * EventBus提起Post请求返回的云会员等级信息
     */
    String sqlUpdateWmlsb = "";

    @Subscribe
    public void getImsCardLand(ImsCardMembers event) {
        String zkfs = "";
        if (event.response.equals("]") || event.response.equals("") || event.response.equals("error")) {
            mProgressBar.setVisibility(View.GONE);
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
        } else {
            Gson gson = new Gson();
            mImsCardMembers = gson.fromJson(event.response, ImsCardMember[].class);
            String cardgrade = mImsCardMembers[0].getCardgrade();
            List<FXHYKSZ> list = DataSupport.select("ZKFS").where("HYKDJ=?", cardgrade).find(FXHYKSZ.class);
            if (list.size() > 0) {
                zkfs = list.get(0).getZKFS();
            }

            String hyj = zkfs.equals("会员价1") ? "hyj" : zkfs.equals("会员价2") ? "hyj2" : zkfs.equals("会员价3") ? "hyj3" : zkfs.equals("会员价4") ? "hyj4" :
                    zkfs.equals("会员价5") ? "hyj5" : zkfs.equals("会员价6") ? "hyj6" : zkfs.equals("会员价7") ? "hyj7" : zkfs.equals("会员价8") ? "hyj8" : zkfs.equals("会员价9") ? "hyj9" : "hyj9";

            //会员价折后价
            String hyjzhj = zkfs.equals("会员价1") ? "hyjzhj" : zkfs.equals("会员价2") ? "hyj2zhj" : zkfs.equals("会员价3") ? "hyj3zhj" : zkfs.equals("会员价4") ? "hyj4zhj" :
                    zkfs.equals("会员价5") ? "hyj5zhj" : zkfs.equals("会员价6") ? "hyj6zhj" : zkfs.equals("会员价7") ? "hyj7zhj" : zkfs.equals("会员价8") ? "hyj8zhj" : zkfs.equals("会员价9") ? "hyj9zhj" : "hyj9zhj";
            Wmslbjb_jiezhang wmlsbjb = (Wmslbjb_jiezhang) mWmlsbjb;
            wmlsbjb.setZKFS(hyj.toUpperCase());//价格策
            /**重新计算打折后的会员价*/
            mTotalMoney = 0f;
            //遍历每一项的会员价
            for (WMLSB wmlsb : mListWmlsb) {
                float hyPrice = getHyPrice(hyj,hyjzhj, wmlsb.getXMBH());
                if (hyPrice == 0) {//非会员价
                    mTotalMoney = mTotalMoney + wmlsb.getXJ();//重算总金额
                } else if (hyPrice != 0) {//会员价
                    if (wmlsb.getDJ()>hyPrice&&hyPrice>0) {//会员价小于目前单价修改折扣方式为会员价
                        String by13 = "会员价" + "(" + cardgrade + ")";
                        wmlsb.setBY13(by13);
                        wmlsb.setDJ(hyPrice > 0 && wmlsb.getDJ() > hyPrice ? hyPrice : wmlsb.getDJ());//未打折，按新的会员价重新计算单价.己打过折扣，看哪个的打折幅度大就取哪个值;
                        wmlsb.setXJ(bigDecimal(wmlsb.getDJ() * wmlsb.getSL()));//重算小计金额
                        sqlUpdateWmlsb = sqlUpdateWmlsb + "update wmlsb set dj=" + wmlsb.getDJ() + ",xj=" + wmlsb.getXJ() + ",by13='" + by13 + "' where xh='" + wmlsb.getXH() + "'|";
                    }
                    mTotalMoney = mTotalMoney + wmlsb.getXJ();//重算总金额
                }
            }
            sqlUpdateWmlsb += "update wmlsbjb set ys='" + mTotalMoney + "' where wmdbh='" + ((Wmslbjb_jiezhang) mWmlsbjb).getWMDBH() + "'|";
            /**更新服务器wmlsb\wmlsbjb表*/
            Post7.getInstance().Http_updateWmlsb(sqlUpdateWmlsb);
        }
    }

    @Subscribe
    public void updatePriceResult(UpdateYhPrice event) {
        mProgressBar.setVisibility(View.GONE);
        if (event.getResult().equals("success")) {
            /**改变应收金额、折扣金额*/
            Moneys.ysjr = bigDecimal2(mTotalMoney);
            Moneys.zkjr = bigDecimal(Moneys.xfzr - Moneys.ysjr);
            Moneys.wfjr = Moneys.ysjr-Moneys.yfjr;
            Intent intent = new Intent(this, YunPayActivity.class);
            intent.putExtra("WMLSBJB", mWmlsbjb);
            intent.putExtra("WMLSB", mListWmlsb);
            intent.putExtra("cards", mImsCardMembers[0]);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
        }
    }

    private float getHyPrice(String hyj, String hyjzhj,String xmbh) {
        float hyPrice = 0f;float hyj1=0f;float hyj2=0f;
        //会员价
        Cursor cursorJyxmsz = DataSupport.findBySQL("select * from jyxmsz where xmbh=?", xmbh);
        for (cursorJyxmsz.moveToFirst(); !cursorJyxmsz.isAfterLast(); cursorJyxmsz.moveToNext()) {
            hyj1 = cursorJyxmsz.getFloat(cursorJyxmsz.getColumnIndex(hyj));
        }
        cursorJyxmsz.close();

        //会员折后价
        SimpleDateFormat dateSdf = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
        SimpleDateFormat timeSdf = new SimpleDateFormat("HHmmss", Locale.CHINA);
        String currentDate = dateSdf.format(new Date());
        String currentTime = timeSdf.format(new Date());
        String Z="1";
        Cursor cursorCxdmxxx = DataSupport.findBySQL("select * from cxdmxxx where xmbh=?", xmbh);
        for (cursorCxdmxxx.moveToFirst(); !cursorCxdmxxx.isAfterLast(); cursorCxdmxxx.moveToNext()) {
            String ksrq = cursorCxdmxxx.getString(cursorCxdmxxx.getColumnIndex("ksrq"));
            String jsrq = cursorCxdmxxx.getString(cursorCxdmxxx.getColumnIndex("jsrq"));
            String kssj = cursorCxdmxxx.getString(cursorCxdmxxx.getColumnIndex("kssj"));
            String jssj = cursorCxdmxxx.getString(cursorCxdmxxx.getColumnIndex("jssj"));
            Z = cursorCxdmxxx.getString(cursorCxdmxxx.getColumnIndex(DateTimes.getWeek().toLowerCase()));

            ksrq =ksrq.substring(0, ksrq.indexOf("T"));
            jsrq = jsrq.substring(0, jsrq.indexOf("T"));
            kssj = kssj.substring(kssj.indexOf("T") + 1, kssj.length()).replaceAll(":", "");
            jssj =jssj.substring(jssj.indexOf("T") + 1, jssj.length()).replaceAll(":", "");

            // 判断 日期 时间
            if (Long.parseLong(ksrq)<=Long.parseLong(currentDate)&&Long.parseLong(currentDate)<=Long.parseLong(jsrq)&&
                    Long.parseLong(kssj)<=Long.parseLong(currentTime)&&Long.parseLong(currentTime)<=Long.parseLong(jssj)) {
                if("1".equals(Z)){//星期
                    hyj2 = cursorCxdmxxx.getFloat(cursorCxdmxxx.getColumnIndex(hyjzhj));
                }
            }
        }
        cursorCxdmxxx.close();

        hyPrice=hyj2>0&&hyj2<hyj1? hyj2:hyj1;
        return hyPrice;
    }

    @OnClick({R.id.btn_cancel, R.id.btn_confirm, R.id.btn_shama})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_confirm:
                mPhone = mEtPhone.getText().toString().trim();
                mPassword = mEtPassword.getText().toString().trim();
                if (mPhone.isEmpty()) {
                    Toast.makeText(this, "请输入电话", Toast.LENGTH_SHORT).show();
                    return;
                }
                mPost6.post_ims_card_members(mPhone, mPassword, mWeid);//发送post请求云会员登录
                mProgressBar.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_shama:
                if(Build.VERSION.SDK_INT>22){
                    if (ContextCompat.checkSelfPermission(this,
                            android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
                        //先判断有没有权限 ，没有就在这里进行权限的申请
                        ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.CAMERA},100);
                        return;
                    }
                }
                Intent intent = new Intent(this, ScanActivity.class);
                startActivityForResult(intent, REQUESTCODE);
                break;
        }
    }

    private float bigDecimal(float f) {
        return BigDecimal.valueOf(f).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
    }
    private float bigDecimal2(float f){
        float roundMoney = 0;
        if(Users.rounding.equals(getString(R.string.rounding_jiao))){
            roundMoney=BigDecimal.valueOf(f).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
        }else if(Users.rounding.equals(getString(R.string.rounding_yuan))){
            roundMoney=BigDecimal.valueOf(f).setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
        }
        return roundMoney;
    }
}
